import json
import os
from typing import Optional, Dict, Any
from dotenv import load_dotenv

import lark_oapi as lark
from lark_oapi.api.calendar.v4 import *

# 加载环境变量
load_dotenv()

def update_calendar_event(
    calendar_id: str,
    event_id: str, 
    user_access_token: str,
    description: Optional[str] = None,
    summary: Optional[str] = None,
    start_time: Optional[Dict[str, Any]] = None,
    end_time: Optional[Dict[str, Any]] = None,
    enable_debug_log: bool = False
) -> Dict[str, Any]:
    """
    更新飞书日历事件的详细信息
    
    Args:
        calendar_id: 日历ID
        event_id: 事件ID
        user_access_token: 用户访问令牌
        description: 事件描述
        summary: 事件标题
        start_time: 开始时间
        end_time: 结束时间
        enable_debug_log: 是否启用调试日志
        
    Returns:
        Dict: 包含更新结果的字典
    """
    try:
        # 创建client
        log_level = lark.LogLevel.DEBUG if enable_debug_log else lark.LogLevel.INFO
        client = lark.Client.builder() \
            .enable_set_token(True) \
            .log_level(log_level) \
            .build()

        # 构建事件更新内容
        event_builder = CalendarEvent.builder()
        
        if description is not None:
            event_builder.description(description)
        if summary is not None:
            event_builder.summary(summary)
        if start_time is not None:
            event_builder.start_time(start_time)
        if end_time is not None:
            event_builder.end_time(end_time)
            
        # 构造请求对象
        request: PatchCalendarEventRequest = PatchCalendarEventRequest.builder() \
            .calendar_id(calendar_id) \
            .event_id(event_id) \
            .user_id_type("user_id") \
            .request_body(event_builder.build()) \
            .build()

        # 发起请求
        option = lark.RequestOption.builder().user_access_token(user_access_token).build()
        response: PatchCalendarEventResponse = client.calendar.v4.calendar_event.patch(request, option)

        # 处理失败返回
        if not response.success():
            error_info = {
                "success": False,
                "code": response.code,
                "msg": response.msg,
                "log_id": response.get_log_id(),
                "raw_response": json.loads(response.raw.content) if response.raw else None
            }
            
            if enable_debug_log:
                lark.logger.error(
                    f"update_calendar_event failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}, resp: \n{json.dumps(error_info['raw_response'], indent=4, ensure_ascii=False)}")
            
            return error_info

        # 处理业务结果
        result = {
            "success": True,
            "data": response.data,
            "log_id": response.get_log_id()
        }
        
        if enable_debug_log:
            lark.logger.info(lark.JSON.marshal(response.data, indent=4))
            
        return result
        
    except Exception as e:
        error_result = {
            "success": False,
            "error": str(e),
            "error_type": type(e).__name__
        }
        
        if enable_debug_log:
            lark.logger.error(f"update_calendar_event exception: {e}")
            
        return error_result


def main():
    """主函数：验证日历事件更新功能"""
    print("=== 飞书日历事件更新测试 ===")
    
    try:
        # 验证环境变量
        calendar_id = "feishu.cn_eimFrJiP8ejNl9D7rPgJle@group.calendar.feishu.cn"
        event_id = "631f7efe-c31e-4701-9912-ac27ba0ad75a_0"
        user_token = "u-cfKIDr80l7dFb7rQYIubFKhl5Rtkg1wXU2004140257y"
        desc="xxxx测试时间戳xxxx"
        
        # 测试更新事件描述
        print("\n[测试] 更新事件描述...")
        result = update_calendar_event(
            calendar_id=calendar_id,
            event_id=event_id,
            user_access_token=user_token,
            description=desc,
            enable_debug_log=True
        )
        
        if result["success"]:
            print("[成功] 事件更新完成")
            print(f"[结果] Log ID: {result.get('log_id')}")
            if result.get("data"):
                print(f"[数据] {json.dumps(result['data'], indent=2, ensure_ascii=False)}")
        else:
            print("[失败] 事件更新失败")
            print(f"[错误] {result.get('msg', result.get('error'))}")
            if result.get("code"):
                print(f"[代码] {result['code']}")
                
    except ValueError as e:
        print(f"[配置错误] {e}")
        print("\n请在 .env 文件中配置以下变量:")
        print("FEISHU_CALENDAR_ID=你的日历ID")
        print("FEISHU_EVENT_ID=你的事件ID")
        print("FEISHU_USER_ACCESS_TOKEN=你的用户访问令牌")
        
    except Exception as e:
        print(f"[异常] {e}")
        
    print("\n=== 测试完成 ===")


if __name__ == "__main__":
    main()